package com.swb.alibaba.common.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>文件  RandomUtil</p>
 * <p>时间  2021-06-30 23:01:31</p>
 *
 * @author swb
 */
public class RandomUtil {
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);
    private static final int EXPONENT = 10;
    private static final int BIT_NUM = 5;
    private static String randomCode = getRandom(5);

    private RandomUtil() {
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getRandom(int count) {
        StringBuilder buf = new StringBuilder();
        String str = "0123456789";
        Random r = new Random();

        for(int i = 0; i < count; ++i) {
            int num = r.nextInt(str.length());
            buf.append(str.charAt(num));
        }

        return buf.toString();
    }

    public static String getRandomLetter(int count) {
        StringBuilder buf = new StringBuilder();
        String str = "ABCDEFGHIJKLMNOPQRSTUVWSYZ";
        Random r = new Random();

        for(int i = 0; i < count; ++i) {
            int num = r.nextInt(str.length());
            buf.append(str.charAt(num));
        }

        return buf.toString();
    }

    public static String getRandomMix(int count) {
        StringBuilder buf = new StringBuilder();
        String str = "0123456789abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ";
        Random r = new Random();

        for(int i = 0; i < count; ++i) {
            int num = r.nextInt(str.length());
            buf.append(str.charAt(num));
        }

        return buf.toString();
    }

    private static String getUniqueID(int power) {
        if ((double)ATOMIC_INTEGER.get() >= Math.pow(10.0D, (double)power)) {
            ATOMIC_INTEGER.set(0);
            refreshRandomCode();
        }

        return Util.lpad(ATOMIC_INTEGER.getAndIncrement() + "", power, "0");
    }

    private static void refreshRandomCode() {
        String preRandomCode = randomCode;
        boolean isOk = false;

        while(!isOk) {
            randomCode = getRandom(5);
            if (!preRandomCode.equals(randomCode)) {
                isOk = true;
            }
        }

    }

    public static String getPrimaryKey() {
        String incrementId = getUniqueID(7);
        return (new SimpleDateFormat("yyMMdd")).format(new Date()) + randomCode + incrementId;
    }

    public static long getNumPrimaryKey() {
        return Long.parseLong(getPrimaryKey());
    }

    public static String getPrimaryKey(String prefix) {
        return prefix + getPrimaryKey();
    }
}
